package com.h5lib.server.protocol;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * FileDirProtocolProvider
 * 文件目录
 * @author farmer
 *
 */
public class FileDirProtocolProvider implements ProtocolProvider{
	
	/**
	 * 根目录
	 */
	private String root;
	
	public FileDirProtocolProvider(){
		this("/");
	}
	
	public FileDirProtocolProvider(String root) {
		this.root = root;
	}
	
	@Override
	public String getProtocol() {
		return "file:";
	}
	
	@Override
	public String getText(String key) {
		byte[] b = getBytes(key) ;
		return new String(b != null ? b : null);
	}
	
	@Override
	public byte[] getBytes(String key) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		InputStream in = getInputStream(key);
		byte[] buff = new byte[1024*10];
		byte[] b = null;
		try {
			int len = -1;
			while ((len = in.read(buff) ) != -1) {
				out.write(buff, 0, len);
			}
			b = out.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return b;
	}
	
	
	@Override
	public InputStream getInputStream(String key) {
		try {
			if(key.startsWith("/")){
				key = key.substring(1, key.length());
			}
			return new FileInputStream(new File(root.endsWith("/")?root.concat(key) : root.concat("/").concat(key)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
